<template>
  <el-dialog draggable title="分配设备" :close-on-click-modal="false" class="yy-modal--custom yy-modal--custom-sub yy-transfer--custom yy-base-item" width="800px" v-model="isVisible" @close="onCancelModel" :show-close="true">
    <div style="text-align: center;">
      <el-transfer
          :titles="['可选设备', '已选设备']"
          v-model="table.selectList"
          filterable
          :data="table.data"
      />
    </div>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancelModel">关闭</el-button>
          <el-button type="primary" :loading="isSubmit" @click="onSave">保存</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {defineExpose, defineEmits, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import ScheduleApi from "@/api/broadcast/schedule";
import {BcScheduleModel} from "@/model/BcScheduleModel";
import DeviceApi from "@/api/queue/DeviceApi";
import {DeviceModel} from "@/model/DeviceModel";
import useUserStore from "@/store/modules/user";

const $emit = defineEmits({
  saveSuccess: () => true
})

const currentSchedule = ref()

const isVisible = ref(false)
const isSubmit = ref(false)

const table = reactive({
  loading: false,
  selectList: [],
  data: []
})

const onShowDialog = (schedule: BcScheduleModel) => {
    isVisible.value = true
    currentSchedule.value = schedule
    listAllDevice()
    listScheduleDevice()
}


const listAllDevice = () => {
    DeviceApi.listDevice(null,currentSchedule.value.deptId, null, 1, 9999).then((res) => {
      if (res.data) {
          table.data = res.data.map(device => Object.assign({
              label: device.name,
              key: device.id,
              origin: device
          }))
      }
    })
}

const listScheduleDevice = () => {
    ScheduleApi.listScheduleDevice(currentSchedule.value.id).then((devices: DeviceModel[]) => {
        table.selectList = devices.map(item => item.id)
    })
}

const onCancelModel = () => {
  isVisible.value = false
}

const onSave = () => {
    isSubmit.value = true
   ScheduleApi.saveScheduleDeviceRelation(currentSchedule.value.id, table.selectList).then(() => {
       ElMessage.success({
           message: '保存成功',
           showClose: true
       })
       isSubmit.value = false
   }, () => isSubmit.value = false)
}
defineExpose({
  onShowDialog
})
</script>
<style scoped lang="scss">
  .yy-base-item {
    &_empl {
      margin-bottom: 15px;
      display: flex;
      white-space: nowrap;
      align-items: center;
      background: #f5f7fa;
      padding: 8px 15px;
    }
  }
</style>